package com.feiyuan.core.controller.admin;

import com.feiyuan.common.exception.BusinessException;
import com.feiyuan.common.result.R;
import com.feiyuan.core.annotation.FeiyuanRequiresPermissions;
import com.feiyuan.core.pojo.entity.AdminRole;
import com.feiyuan.core.service.AdminRoleService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 后台角色管理
 * @author Xupf
 */
@Api(tags = "后台角色管理")
@RestController
@RequestMapping("/admin/core/adminRole")
@Slf4j
//@CrossOrigin
public class AdminRoleController {

    @Autowired
    private AdminRoleService adminRoleService;

    @ApiOperation("查询所有的角色信息")
    @GetMapping("/list")
    @FeiyuanRequiresPermissions("admin:role:list")
    public R list(@RequestParam("pageNo") Integer pageNo, @RequestParam("pageSize") Integer pageSize,
                  @RequestParam("roleName") String roleName, @RequestParam("roleCode") String roleCode) {
        IPage<AdminRole> pages = adminRoleService.listPage(pageNo, pageSize, roleName, roleCode);
        return R.ok().data("pages", pages);
    }

    @ApiOperation("查询单个信息")
    @GetMapping("/info/{id}")
    @FeiyuanRequiresPermissions("admin:role:info")
    public R info(@PathVariable Long id) {
        return R.ok().data("info", adminRoleService.getById(id));
    }

    @ApiOperation("保存或者修改角色信息")
    @PostMapping("/saveOrUpdate")
    @FeiyuanRequiresPermissions("admin:role:saveOrUpdate")
    public R saveOrUpdate(
            @ApiParam(value = "角色表对象", required = true)
            @RequestBody AdminRole adminRole
    ) {
        boolean b = adminRoleService.saveOrUpdateRole(adminRole);
        if (b) {
            return R.ok().message("更新成功");
        } else {
            return R.error().message("更新失败");
        }
    }

    @ApiOperation("删除角色信息")
    @PostMapping("/remove/{id}")
    @FeiyuanRequiresPermissions("admin:role:remove")
    public R remove(@PathVariable Long id) {
        AdminRole role = adminRoleService.getById(id);
        if (role.getRoleCode().equals("SYSADMIN")) {
            throw new BusinessException("超级管理员角色不支持删除", -101);
        }
        boolean b = adminRoleService.removeById(id);
        if (b) {
            return R.ok().message("删除成功");
        } else {
            return R.error().message("删除失败");
        }
    }

    @ApiOperation("查询所有角色")
    @GetMapping("/getRoleAll")
    @FeiyuanRequiresPermissions("admin:role:getRoleAll")
    public R getRoleAll() {
        List<AdminRole> list = adminRoleService.list();
        return R.ok().data("roles", list);
    }
}
